<template>
  <a-button @click="up">升序</a-button>
  <a-button @click="down">降序</a-button>
  <a-list item-layout="horizontal" :data-source="sortedData">
    <template #renderItem="{ item, index }">
      <a-list-item>
        <a-list-item-meta
          description="Ant Design, a design language for background applications, is refined by Ant UED Team">
          <template #title>
            {{ item.index }}
          </template>
          <template #avatar>
            <a-input-search :value="item.index" placeholder="输入新的索引值"
              @search="updateIndex(item, $event)"></a-input-search>
          </template>
        </a-list-item-meta>
      </a-list-item>
    </template>
  </a-list>
</template>
<script>
import _ from 'lodash'; // 引入 lodash 库进行深拷贝
let data = [
  { index: 1, title: 'Ant Design Title 1' },
  { index: 1, title: 'Ant Design Title 1' },
  { index: 1, title: 'Ant Design Title 1' },
  { index: 1, title: 'Ant Design Title 1' },
  { index: 5, title: 'Ant Design Title 2' },
  { index: 6, title: 'Ant Design Title 3' },
  { index: 9, title: 'Ant Design Title 4' },
]
export default {
  data() {
    return {
      data,
      sortOrder: 'asc', // 默认为升序
    };
  },
  computed: {
    sortedData() {
      // 根据当前的排序顺序返回排序后的数据
      const sortFunction = (a, b) => {
        if (this.sortOrder === 'asc') {
          return a.index - b.index;
        } else {
          return b.index - a.index;
        }
      };
      return [...this.data].sort(sortFunction);
    },
  },
  methods: {
    up() {
      this.sortOrder = 'asc';
    },
    down() {
      this.sortOrder = 'desc';
    },
    updateIndex(item, newValue) {
      // 更新指定项的 index 值
      const newIdx = parseInt(newValue, 10);
      if (!isNaN(newIdx)) {
        // 使用 lodash 的深拷贝方法
        const newData = _.cloneDeep(this.data);

        // 找到要更新的项并更新其 index 值
        const itemToUpdate = newData.find(i => i === item);
        if (itemToUpdate) {
          itemToUpdate.index = newIdx;
        }

        console.log(newData);
        // 更新 data 数组
        this.data = newData;
        // 重新排序数据
        this.$nextTick(() => {
          this.up(); // 或者 this.down()，取决于你希望保持哪种排序
        });
      }
    },
  },
};
</script>